package cn.silver.module.web.service.impl;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.silver.framework.core.constant.GlobalConstants;
import cn.silver.framework.core.enums.SystemResultEnums;
import cn.silver.framework.core.enums.SystemStatusEnums;
import cn.silver.framework.core.exception.user.CaptchaExpireException;
import cn.silver.framework.core.exception.user.UserException;
import cn.silver.framework.core.utils.MessageUtils;
import cn.silver.framework.core.utils.StringUtils;
import cn.silver.framework.core.utils.ValidatorUtils;
import cn.silver.framework.core.validate.auth.EmailGroup;
import cn.silver.framework.redis.utils.RedisUtils;
import cn.silver.framework.satoken.enums.GrantTypeEnums;
import cn.silver.framework.satoken.model.LoginUser;
import cn.silver.framework.satoken.utils.LoginHelper;
import cn.silver.framework.tenant.helper.TenantHelper;
import cn.silver.module.authority.bean.ClientBean;
import cn.silver.module.system.bean.UserBean;
import cn.silver.module.system.domain.SysUser;
import cn.silver.module.system.mapper.SysUserMapper;
import cn.silver.module.web.enums.LoginType;
import cn.silver.module.web.model.LoginEmailModel;
import cn.silver.module.web.model.LoginModel;
import cn.silver.module.web.model.LoginResultModel;
import cn.silver.module.web.service.IAuthStrategy;
import cn.silver.module.web.service.SysLoginService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 邮件认证策略
 *
 * @author Michelle.Chung
 */
@Slf4j
@Service("email" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class EmailAuthStrategy implements IAuthStrategy {

    private final SysLoginService loginService;
    private final SysUserMapper userMapper;

    @Override
    public void validate(LoginModel loginModel) {
        LoginEmailModel model = loginModel.getEmail();
        ValidatorUtils.validate(model, EmailGroup.class);
    }

    @Override
    public LoginResultModel doLogin(ClientBean client, LoginModel loginModel) {
        LoginEmailModel model = loginModel.getEmail();
        String tenantId = loginModel.getTenantId();
        String email = model.getEmail();
        // 通过邮箱查找用户
        UserBean user = loadUserByEmail(tenantId, email);

        loginService.checkLogin(LoginType.EMAIL, tenantId, user, client, () -> !validateEmailCode(tenantId, model.getEmailCode(), user, client));
        // 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了
        LoginUser loginUser = loginService.buildLoginUser(user);
        SaLoginModel login = new SaLoginModel();
        login.setDevice(client.getDeviceType());
        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期
        login.setTimeout(client.getTimeout());
        login.setActiveTimeout(client.getActiveTimeout());
        login.setExtra(LoginHelper.CLIENT_KEY, client.getCode());
        // 生成token
        LoginHelper.login(loginUser, login);

        loginService.recordLogininfor(GrantTypeEnums.AUTH_MAIL.getCode(), loginUser.getTenantId(), user, client, SystemResultEnums.SUCCESS.getCode(),
                MessageUtils.message("user.login.success"));
        LoginResultModel loginResultModel = new LoginResultModel();
        loginResultModel.setAccessToken(StpUtil.getTokenValue());
        loginResultModel.setExpireIn(StpUtil.getTokenTimeout());
        loginResultModel.setClientId(client.getId());
        return loginResultModel;
    }

    /**
     * 校验邮箱验证码
     */
    private boolean validateEmailCode(String tenantId, String code, UserBean user, ClientBean client) {
        String value = RedisUtils.getCacheObject(GlobalConstants.CAPTCHA_CODE_KEY, user.getEmail());
        if (StringUtils.isBlank(value)) {
            loginService.recordLogininfor(GrantTypeEnums.AUTH_MAIL.getCode(), tenantId, user, client, SystemResultEnums.FAIL.getCode(), MessageUtils.message("user.jcaptcha.expire"));
            throw new CaptchaExpireException();
        }
        return value.equals(code);
    }

    private UserBean loadUserByEmail(String tenantId, String email) {
        SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>().select(SysUser::getEmail, SysUser::getStatus)
                .eq(TenantHelper.isEnable(), SysUser::getId, tenantId)
                .eq(SysUser::getEmail, email));
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", email);
            throw new UserException("user.not.exists", email);
        } else if (SystemStatusEnums.DISABLED.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", email);
            throw new UserException("user.blocked", email);
        }
        if (TenantHelper.isEnable()) {
            return userMapper.selectTenantUserByEmail(email, tenantId);
        }
        return userMapper.selectUserByEmail(email);
    }

}
